import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';
import { ICheckTask } from 'app/shared/model/check-task.model';
import { CheckTaskService } from './check-task.service';

@Component({
    selector: 'jhi-check-task-update',
    templateUrl: './check-task-update.component.html'
})
export class CheckTaskUpdateComponent implements OnInit {
    checkTask: ICheckTask;
    isSaving: boolean;
    startTime: string;
    endTime: string;

    constructor(protected checkTaskService: CheckTaskService, protected activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ checkTask }) => {
            this.checkTask = checkTask;
            this.startTime = this.checkTask.startTime != null ? this.checkTask.startTime.format(DATE_TIME_FORMAT) : null;
            this.endTime = this.checkTask.endTime != null ? this.checkTask.endTime.format(DATE_TIME_FORMAT) : null;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        this.checkTask.startTime = this.startTime != null ? moment(this.startTime, DATE_TIME_FORMAT) : null;
        this.checkTask.endTime = this.endTime != null ? moment(this.endTime, DATE_TIME_FORMAT) : null;
        if (this.checkTask.id !== undefined) {
            this.subscribeToSaveResponse(this.checkTaskService.update(this.checkTask));
        } else {
            this.subscribeToSaveResponse(this.checkTaskService.create(this.checkTask));
        }
    }

    protected subscribeToSaveResponse(result: Observable<HttpResponse<ICheckTask>>) {
        result.subscribe((res: HttpResponse<ICheckTask>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    protected onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    protected onSaveError() {
        this.isSaving = false;
    }
}
